/* 封装axios用于发送请求 */
import axios from "axios";
import store from "@/store";
// import { removeToken } from "./storage";
import router from "@/router";

// 创建一个新的axios实例
const request = axios.create({
  baseURL: "https://slwl-geteway.itheima.net/manager/",
  timeout: 5000,
});

// 添加请求拦截器
request.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么
    const token = store.state.user.token;
    if (token) {
      config.headers.Authorization = token;
    }
    return config;
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
request.interceptors.response.use(
  function (response) {
    // 对响应数据做点什么
    const { code, msg } = response.data;
    if (code === 200) {
      return response.data;
    } else {
      this.$message.error(msg);
      return Promise.reject(new Error(msg));
    }
  },
  function (error) {
    if (error.response.status === 401) {
      store.commit("user/removeToken");
      router.push("/login");
      this.$message.error("token过期");
    } else {
      return Promise.reject(error);
    }
  }
);

export default request;
